package rm.metrology.server;

import java.util.ArrayList;
import java.util.List;

import rm.metrology.shared.CostEntity;


public class CostDAO extends BaseDAO {

	
	private static final CostDAO fInstance = new CostDAO();
	
	public static final CostDAO getInstance() {
		return fInstance;
	}
	

	private boolean isCacheDirty = true;
	
	private List<CostEntity> fCostings = new ArrayList<CostEntity>();
	
	private CostDAO() {
	}
	
	public List<CostEntity> insert(CostEntity e) {
		validateNationalUser(UserDAO.getInstance().getCurrent());
		validate(e);
		ofy().put(e);
		emailStaff("Costing Added", "<p/>Costing Details :<p/>" + e.toString());
		isCacheDirty = true;
		return selectAll();
	}
	
	public List<CostEntity> delete(Long id) {
		validateNationalUser(UserDAO.getInstance().getCurrent());
		CostEntity eDB = ofy().get(CostEntity.class, id);
		ofy().delete(eDB);
		emailStaff("Costing Removed", "<p/>Costing Details :<p/>" + eDB.toString());
		isCacheDirty = true;
		return selectAll();
	}	
	
	public List<CostEntity> selectAll() {
		if (isCacheDirty) {
			fCostings.clear();
			fCostings.addAll(ofy().query(CostEntity.class).order("fCalibType").order("fRangeStart").list());
			isCacheDirty = false;
		}
		return fCostings;
	}

}
